#include "head.h"


bool is_have_dir(MYSQL* mysql, const char* dir_path, int uid);
int create_dir(MYSQL* mysql, const char* path, const char* dir_path, int uid, const char* cmd);
// mkdir
int to_mkdir(messenger_t* msg, int sock_fd, MYSQL* mysql)
{
    // 切割参数
    char* path = msg->args;
    char* cmd = path;
    while(*cmd != '&') ++cmd;
    *cmd++ = '\0';

    // 得到用户的id // 解密 TOKEN
    int uid = 0;
    l8w8jwt_uid(msg->token, &uid);

    // 查看有无这个文件夹
    char dir_path[100] = {0};
    if(strcmp(path, "/") == 0)
        sprintf(dir_path, "%s%s", path, cmd);
    else
        sprintf(dir_path, "%s/%s", path, cmd);
    if(is_have_dir(mysql, dir_path, uid))
    {
        send(sock_fd, "faileded", 8, MSG_NOSIGNAL);
        return -1;
    }

    // 创建文件夹
    create_dir(mysql, path, dir_path, uid, cmd);
    send(sock_fd, "succeedd", 8, MSG_NOSIGNAL);
    
    return 0;
}

bool is_have_dir(MYSQL* mysql, const char* dir_path, int uid)
{
    char sql[200] = {0};
    sprintf(sql, "select * from file where file_usr = %d and file_path = '%s' and file_exist = 0 and file_type = 1", uid, dir_path);
    LOG_MSG(sql);
    if(mysql_query(mysql, sql) != 0)
        LOG_MSG("mysql_query");

    // sql 执行成功， 取结果
    MYSQL_RES* res = mysql_store_result(mysql);
    if(res == NULL || mysql_num_rows(res) == 0)
    {   
        // 该用户目录下没有这个文件夹
        mysql_free_result(res);
        return false;
    }

    // 该用户目录下有这个文件夹
    mysql_free_result(res);
    return true;
}

// 创建文件夹
int create_dir(MYSQL* mysql, const char* path, const char* dir_path, int uid, const char* cmd)
{

    char sql[200] = {0};
    sprintf(sql, "select * from file where file_usr = %d and file_path = '%s' and file_exist = 0 and file_type = 1", uid, path);
    LOG_MSG(sql);
    if(mysql_query(mysql, sql) != 0)
        LOG_MSG("mysql_query");

    // sql 执行成功， 取结果
    MYSQL_RES* res = mysql_store_result(mysql);
    MYSQL_ROW line = mysql_fetch_row(res);

    // 得到父路径的文件 id
    int father_id = atoi(line[0]);
    mysql_free_result(res);

    // 插入数据
    bzero(sql, sizeof(sql));
    sprintf(sql, "insert into file values (NULL, '%s', %d, '%s/', 0, NULL, 1, %d, 0, -1)", dir_path, uid, cmd, father_id);
    LOG_MSG(sql);
    if(mysql_query(mysql, sql) != 0)
        LOG_MSG("mysql_query");
    
    return 0;
}